package com.studio49.exmple.service.web.sys.impl;

import java.util.ArrayList;
import java.util.List;

import com.studio49.exmple.common.constant.SysConstant;
import com.studio49.exmple.entity.web.sys.Menus;
import com.studio49.exmple.entity.web.sys.Role;
import com.studio49.exmple.mapper.web.sys.MenuMapper;
import com.studio49.exmple.mapper.web.sys.RoleMapper;
import com.studio49.exmple.service.web.sys.MenusService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Joiner;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class MenusServiceImpl implements MenusService {
	
	@Autowired
	private MenuMapper menuMapper;
	
	@Autowired
	private RoleMapper roleMapper;

	@Override
	public List<Menus> findAll() {
		
		Example example = new Example(Menus.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("isOpen", 1);
		criteria.andEqualTo("isDeleted", 0);
		example.orderBy("orderBy");
		List<Menus> list = menuMapper.selectByExample(example);
		return list;
	}

	@Override
	public List<Menus> findByUserId(Long userId) {
		
		List<Role> roles = roleMapper.findByUserId(userId);
		if(CollectionUtils.isNotEmpty(roles)) {
			List<Long> ids = new ArrayList<>();
			for(Role role : roles) {
				Long id = role.getId();
				String roleKey = role.getRoleKey();
				//管理员，所有菜单
				if(SysConstant.ROLE_KEY_ADMIN.equals(roleKey)) {
					return this.findAll();
				}
				ids.add(id);
			}
			String roleIds = Joiner.on(",").join(ids);
			List<Menus> list = menuMapper.findByRoleIds(roleIds);
			return list;
		}
		return null;
	}

}
